package net.jkdmanager.agent.services.configuration;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import net.jkdmanager.agent.services.agent.AgentStatusService;
import net.jkdmanager.common.api.messages.ConfigurationMessage;
import net.jkdmanager.common.api.messages.ConfigurationRequestMessage;
import net.jkdmanager.common.api.model.Application;
import net.jkdmanager.common.services.messaging.MessageListener;
import net.jkdmanager.common.services.messaging.MessagingService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * This class is responsible for providing configuration.
 * Either from local cache storage or obtained from server. 
 *  
 * @author Honza
 *
 */
@Service("agentConfigurationService")
public class AgentConfigurationServiceImpl implements AgentConfigurationService, MessageListener {
	
	@Autowired
	private AgentStatusService agentStatusService;
	
	@Autowired
	private MessagingService messagingService;
	
	//@Value("#{systemProperties.agentId}")
	//private String agentId;
	
	private List<Application> applications;
	
	public void receiveMessage(Serializable message) {
		if (message instanceof ConfigurationMessage) {
			configurationUpdated((ConfigurationMessage)message);
		}
	}
	
	private void configurationUpdated(ConfigurationMessage configurationMessage) {
		System.out.println("Received configuration message");
		
		boolean configurationBefore = applications != null;
		applications = configurationMessage.getApplications();
		if (!configurationBefore) {
			agentStatusService.configurationObtained();
		}
		
	}

	@PostConstruct
	public void init() {
		//TODO: following method should be called asynchrnously
		//otherwise agent will not start if server is not running
		applications = new ArrayList<Application>();
		refreshConfiguration();
	}
	
	private void refreshConfiguration() {
		final ConfigurationRequestMessage configurationRequestMessage = new ConfigurationRequestMessage();
		messagingService.sendMessage(configurationRequestMessage);
	}
	
	public List<Application> getAllApplications() {
		return applications;
	}
	
	public Application getApplication(long appId) {
		
		for (Application app : applications) {
			if (app.getId() == appId) {
				return app;
			}
		}
		return null;
		
	}
	
	@PreDestroy
	public void destroy() {
		
	}
	
}
